package com.y.fund.web.lgn;

import java.util.LinkedHashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.github.xiaoymin.knife4j.annotations.ApiSort;
import com.y.fund.aacore.data.DataVo;
import com.y.fund.aacore.enums.BoolVal;
import com.y.fund.aacore.enums.LoginState;
import com.y.fund.consts.ConstAttr;
import com.y.fund.domain.mem.MB13UserInfo;
import com.y.fund.domain.mem.MB15LoginRecord;
import com.y.fund.handler.CurrLgnUserVo;
import com.y.fund.service.mem.UserService;
import com.y.fund.utils.DateTimeUtil;
import com.y.fund.utils.MD5Util;
import com.y.fund.utils.RedisUtil;
import com.y.fund.utils.StrUtil;
import com.y.fund.web.BaseController;
import com.y.fund.web.aavo.com.LgnUserVo;
import com.y.fund.web.aavo.mem.ChangePwdVo;
import com.y.fund.web.aavo.mem.LoginInfo;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ApiSort(1)
@RestController
@RequestMapping(value="api/lgn", produces = MediaType.APPLICATION_JSON_VALUE)
@Tag(name = "登录管理")
public class LoginController extends BaseController{

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	UserService userService;


	static LinkedHashMap<String, String> LastOptTimeOrderMap = new LinkedHashMap<String, String>();
	static{
		LastOptTimeOrderMap.put("lastOptTime", "desc");
	}

	@Operation(summary = "用户密码登录")
	@PostMapping(value = "account") 
    public DataVo lgn(@RequestBody LoginInfo inAccount, HttpServletRequest req) throws Exception{
		if(StrUtil.isBlankIncNullStr(inAccount.getLgnName())
				|| StrUtil.isBlankIncNullStr(inAccount.getLgnPwd())
		        || StrUtil.isBlankIncNullStr(inAccount.getClientType())) {
			return DataVo.FailMustParam("lgnName, lgnPwd, clientType");
		}
		
		MB13UserInfo exp = new MB13UserInfo();
		exp.setLgnName(inAccount.getLgnName());
		MB13UserInfo user = commService.findObjByExample(exp, null);
		if(null == user) {
			return DataVo.Fail(41204, "用户信息不存在");
		}
		String pwd = MD5Util.encode(inAccount.getLgnPwd());
		if(null==pwd || !pwd.equals(user.getLgnPwd())) {
			return DataVo.Fail("登录密码错误");
		}
		
		if(null==user || !BoolVal.IsYes(user.getEnabled())) {
			return DataVo.Fail("用户信息不存在或此用户禁止登录");
		}

		Map<String, Object> lgnInfo = recordLgnTrace(inAccount.getLgnName(), user, inAccount.getClientType(), ConstAttr.LGN_EXPIRES_SECOND);
		if(null==user.getChangePwdTime() || user.getChangePwdTime()<1L) {
			lgnInfo.put("needChgPwd", 1);
		}
		
		return DataVo.Success(lgnInfo);
	}

	@PostMapping("chgpwd")
	@Operation(summary = "修改密码")
	@ApiOperationSupport(order = 4)
	public DataVo updtStaffIngroalNull(@RequestBody @Validated ChangePwdVo cp) throws Exception{
		LgnUserVo luv = CurrLgnUserVo.Get();
		MB13UserInfo user = null;
		if(null != luv) {
			user = commService.findObjById(MB13UserInfo.class, luv.getUserId());
		}else if(StrUtil.NotBlankIgnoreNullStr(cp.getLgnName())){
			MB13UserInfo exp = new MB13UserInfo();
			exp.setLgnName(cp.getLgnName());
			user = commService.findObjByExample(exp, null);
		}
		if(null == user) {
			return DataVo.Fail("用户信息不存在");
		}
		
		String pwd = MD5Util.encode(cp.getOldPwd());
		if(null==pwd || !pwd.equals(user.getLgnPwd())) {
			return DataVo.Fail("原登录密码错误");
		}
		MB13UserInfo updt = new MB13UserInfo();
		updt.setId(user.getId());
		updt.setLgnPwd(MD5Util.encode(cp.getNewPwd()));
		updt.setChangePwdTime(System.currentTimeMillis());
		
		if(commService.updtByIdIgnoreNull(updt)) {
			return DataVo.Success(user.getId());
		}else {
			return DataVo.Fail("密码修改失败");
		}
	}
	
	@Operation(summary = "退出当前用户")
	@ApiOperationSupport(order =3)
	@PostMapping(value = "logout") 
    public DataVo logout() throws Exception{
		LgnUserVo luv = CurrLgnUserVo.Get();
		if(null==luv || StrUtil.isBlankIncNullStr(luv.getLgnId())) {
			return DataVo.Success();
		}

		redisUtil.del(LgnUserVo.GetCacheKey(luv.getClientType(), luv.getUserId()));

		try {
			MB15LoginRecord updt = MB15LoginRecord.ForUpdt(luv.getLgnId());
			updt.setLogoutTime(DateTimeUtil.NowTime());
			updt.setStatus(LoginState.Logout.getVal());
	    	commService.updtByIdIgnoreNull(updt);
		}catch (Exception ex) {
			ex.printStackTrace();
		}
		return DataVo.Success();
	}


	
}
